// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-16 20:28
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.toList;

public class ThirdMax {
    public int thirdMax(int[] nums) {
        List<Integer> res = IntStream.of(nums).distinct().sorted().boxed().collect(toList());
        int n = res.size();
        if (n == 1) {
            return nums[0];
        } else if (n == 2) {
            return Math.max(res.get(0), res.get(1));
        }
        return res.get(n - 3);
    }

//        Arrays.sort(nums);
//        int n = nums.length;
//        if (n < 3) {
//            return nums[n - 1];
//        } else {
//            return getLastThird(nums, n);
//        }


    /**
     * 返回升序数组中第三大的元素
     *
     * @param nums
     * @param n
     * @return
     */
    private int getLastThird(int[] nums, int n) {
        int k = 2, cur = n - 2;
        while (k > 0) {
            if (nums[cur] != nums[cur + 1]) {
                k--;
            }
            if (k == 0) {
                break;
            }
            cur--;
        }
        return nums[cur];
    }

    @Test
    public void shout() {
        //int[] test = {2, 2, 1, 3};
        int[] test = {1, 1, 2};
        System.out.println(thirdMax(test));
    }
}
